"""
统计相关的数据模型
- AppStats: 应用统计表，记录应用的使用统计信息
- UserQuota: 用户配额表，记录用户的使用配额
"""

from datetime import datetime, UTC
from sqlalchemy import Column, String, DateTime, Integer, ForeignKey, Enum, text
from sqlalchemy.orm import relationship
import enum
from dao.postgresql_connect import Base

class QuotaType(enum.Enum):
    """配额类型枚举"""
    DAILY = "daily"
    MONTHLY = "monthly"
    TOTAL = "total"

class AppStats(Base):
    """应用统计表"""
    __tablename__ = 'app_stats'

    id = Column(String(36), primary_key=True)
    app_id = Column(String(36), ForeignKey('apps.id'), nullable=False, comment='应用ID')
    total_installs = Column(Integer, default=0, comment='总安装数')
    active_users = Column(Integer, default=0, comment='活跃用户数')
    total_messages = Column(Integer, default=0, comment='总消息数')
    total_tokens = Column(Integer, default=0, comment='总token数')
    date = Column(DateTime, nullable=False, comment='统计日期')
    created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False, comment='创建时间')
    updated_at = Column(DateTime, default=lambda: datetime.now(UTC), server_default=text('CURRENT_TIMESTAMP'), nullable=False, comment='更新时间')

    # 关系
    app = relationship('App', back_populates='stats')

class UserQuota(Base):
    """用户配额表"""
    __tablename__ = 'user_quotas'

    id = Column(String(36), primary_key=True)
    user_id = Column(String(36), ForeignKey('users.id'), nullable=False, comment='用户ID')
    app_id = Column(String(36), ForeignKey('apps.id'), nullable=False, comment='应用ID')
    quota_type = Column(Enum(QuotaType), nullable=False, comment='配额类型')
    limit = Column(Integer, nullable=False, comment='限制数量')
    used = Column(Integer, default=0, comment='已使用数量')
    reset_at = Column(DateTime, nullable=False, comment='重置时间')
    created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False, comment='创建时间')
    updated_at = Column(DateTime, default=lambda: datetime.now(UTC), server_default=text('CURRENT_TIMESTAMP'), nullable=False, comment='更新时间')

    # 关系
    user = relationship('User', back_populates='quotas')
    app = relationship('App', back_populates='quotas') 